package com.sparrow.common.value;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class EnumUtil {
    /**
     * 缓存每个枚举类的 value -> 枚举实例 映射
     */
    private static final Map<Class<? extends EnumValue>, Map<Integer, ? extends EnumValue>> cache = new ConcurrentHashMap<>();


    @SuppressWarnings("unchecked")
    public static <T extends EnumValue> T valueOf(Class<T> enumClass, int value) {
        Map<Integer, T> map = (Map<Integer, T>) cache.computeIfAbsent(enumClass, cls -> {
            Map<Integer, T> m = new ConcurrentHashMap<>();
            for (EnumValue enumConstant : cls.getEnumConstants()) {
                m.put(enumConstant.value(), (T) enumConstant);
            }
            return m;
        });
        return map.get(value);
    }

    public static boolean isEnum(Class<?> type) {
        return type.isEnum();
    }

    public static Object parseEnum(Class<?> type, String str) {
        if (!type.isEnum()) {
            throw new IllegalArgumentException("Type is not an enum: " + type);
        }
        Class<? extends Enum> enumType = (Class<? extends Enum>) type;
        return Enum.valueOf(enumType, str);
    }


}
